package com.zlm.sync;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author: 郑
 * 异步调用
 * CompletableFuture
 * //异步执行
 * 成功回调
 * 失败回调
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(5);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName() + "runAsync");
//        });
//        System.out.println("11111");
//        completableFuture.get();
        //又返回值的异步回调
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
            int a=10/0;
            return 1024;
        });

        Integer integer = completableFuture.whenComplete((data, msg) -> {
            System.out.println("data =>" + data);//正常结果
            System.out.println("msg => " + msg);//错误信息
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 500;
        }).get();
        System.out.println(integer);
    }
}
